 package org.hitchhike.core.config;

import java.util.Arrays;
import java.util.List;

import org.hitchhike.core.security.CustomUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  private static List<String> DEFAULT_IGNORED = Arrays.asList("/css/**", "/js/**", "/images/**",
      "/webjars/**", "/**/favicon.ico", "/assets/**", "/register", "/choose", "/h2-console/**","/api/**","/rest/**");

  @Bean 
  UserDetailsService customUserService() {
    return new CustomUserService();
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
        .antMatchers(DEFAULT_IGNORED.toArray(new String[DEFAULT_IGNORED.size()])).permitAll()
        .anyRequest().authenticated()
        .and()
      .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/loginForm")
        .permitAll()
        .and()
      .logout()
        .logoutUrl("/logout")
        .permitAll()
        .and()
        /**
         * 4，iframe加载问题（x-frame-options）
         * 
         * 当我们的jsp页面中使用了iframe时，可能出现该iframe中的内容无法加载的问题。
         * 
         * 这是因为SpringSecurity提供的HeaderWriterFilter为response添加安全header信息。
         * 
         * 其中就有一项是：X-Frame-Options选项。
         * 
         * 该选项有三个值：
         * 
         * DENY：浏览器拒绝当前页面加载任何frame页面。
         * 
         * SAMEORIGHT：允许加载本站点内的页面。
         * 
         * ALLOW-FROM：允许frame加载任何页面。
         * 
         * SpringSecurity中默认设置X-Frame-Options的值为DENY
         */
       .headers()
         .frameOptions().disable()
         .and()
       .csrf().disable();
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(customUserService());
  }

}
